package cn.touna.jss.modules.custom.auth;

import cn.touna.risk.api.enums.SystemErrorCodeEnum;
import cn.touna.jss.common.factory.ResponseFactory;
import cn.touna.jss.common.util.ValidUtil;
import cn.touna.jss.modules.adapter.ApiMapping;
import cn.touna.jss.modules.credit.entity.CreditNameAuthEntity;
import cn.touna.jss.modules.credit.service.AuthNameService;
import cn.touna.jss.modules.custom.auth.entity.AuthRealNameEntity;
import cn.touna.jss.modules.third.tx.TianXingService;
import cn.touna.jss.modules.third.tx.entity.TianXingRequestEntity;
import cn.touna.jss.modules.third.zhongan.ZhonganService;
import cn.touna.jss.modules.third.zhongan.entity.ZhonganRequestEntity;
import cn.touna.risk.api.domain.Response;
import com.alibaba.fastjson.JSONObject;
import com.touna.loan.log.service.TracerContextUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * 实名认证调用组件
 * Created by wuwc
 */
@Service
public class AuthRealNameService {
    private static final Logger logger = LogManager.getLogger(AuthRealNameService.class);

    @Autowired
    private TianXingService tianXingService;

    @Autowired
    private ZhonganService zhonganService;

    @Autowired
    private AuthNameService authNameService;

    private static final String COMPARE_SAME = "SAME";

    /**
     * 调用天行实名认证
     * @param authRealNameEntity
     * @return
     */
    @ApiMapping(value = "authRealName.txIdCardVerify",desc = "复合数据.实名认证（天行/众安）")
    public Response txIdCardVerify(AuthRealNameEntity authRealNameEntity) {
        //减少异常的抛出
        Response response = ValidUtil.valid(authRealNameEntity);
        if(response != null){
            return response;
        }

        response = new Response();
        ValidUtil.checkRequestParams(authRealNameEntity);
        try {
            CreditNameAuthEntity creditNameAuthEntity = authNameService.queryNameAuth(authRealNameEntity.getIdCard(), authRealNameEntity.getName());
            logger.info("PRO 调用【身份证实名认证-txIdCardVerify】数据库查询数据:{}", creditNameAuthEntity);
            if (creditNameAuthEntity != null) {
                return response.success(SystemErrorCodeEnum.SYSTEM_REQUEST_SUCC, creditNameAuthEntity);
            }

            response = zhonganAuthRealIdentity(authRealNameEntity);
            logger.info("PRO 调用【众安身份证实名认证】结果,result:{}", response);
            if (response.checkIfSuccess()) {
                if (isSame(response)) {
                    authNameService.saveAuthData(response);
                }
                return response;
            }
            TianXingRequestEntity requestEntity = new TianXingRequestEntity();
            BeanUtils.copyProperties(authRealNameEntity, requestEntity);
            response = tianXingService.getIdCardVerifyData(requestEntity);
            if (response.checkIfSuccess()) {
                if (isSame(response)) {
                    authNameService.saveAuthData(response);
                }
            }
            return response;
        } catch (Exception e) {
            logger.error("PRO 调用【身份证实名认证-txIdCardVerify】异常,params:{}，msg:{}", authRealNameEntity, e.getMessage());
            return ResponseFactory.fail(SystemErrorCodeEnum.CRS_SYSTEM_FAILED, e.getMessage());
        }
    }

    /**
     * 调用众安身份认证
     * @param authRealNameEntity
     * @return
     */
    private Response zhonganAuthRealIdentity(AuthRealNameEntity authRealNameEntity) {
        JSONObject resultJson = new JSONObject();
        Response response = null;
        try {
            ZhonganRequestEntity.AuthRealIdentityRequest requestEntity = new ZhonganRequestEntity.AuthRealIdentityRequest();
            BeanUtils.copyProperties(authRealNameEntity, requestEntity);
            requestEntity.setRequestNo(TracerContextUtil.getTraceId());
            response = zhonganService.authRealIdentity(requestEntity);
            if (response.checkIfSuccess()) {
                JSONObject jsonObject = JSONObject.parseObject(response.getData().toString());
                JSONObject head = (JSONObject) jsonObject.get("head");
                String rspCode = (String) head.get("rspCode");
                JSONObject body = jsonObject.getJSONObject("body");
                JSONObject rspInfo = body.getJSONObject("rspInfo");
                JSONObject reqInfo = (JSONObject) body.get("reqInfo");
                String quotaValue = (String) rspInfo.get("quotaValue");
                resultJson.put("name", reqInfo.get("name"));
                resultJson.put("idNo", authRealNameEntity.getIdCard());
                if (rspCode.equals("0000")) {
                    if (quotaValue.equals("Y")) {
                        resultJson.put("compareStatus", "SAME");
                        resultJson.put("compareStatusDesc", "一致");
                    } else {
                        resultJson.put("compareStatus", "DIFFERENT");
                        resultJson.put("compareStatusDesc", "不一致");
                    }
                    response.success(SystemErrorCodeEnum.SYSTEM_REQUEST_SUCC);
                    response.setData(resultJson);
                    response.setMsg("请求成功");
                }
            } else {
                response.fail();
            }
            return response;
        } catch (Exception e) {
            logger.error("PRO 调用【众安身份认证 - authRealIdentity】异常，params:{},msg:{}", authRealNameEntity, e.getMessage());
            return ResponseFactory.fail(SystemErrorCodeEnum.CRS_SYSTEM_FAILED, e.getMessage());
        }
    }

    private boolean isSame(Response response) {
        JSONObject jsonObject = JSONObject.parseObject(response.getData().toString());
        String compareStatus = (String) jsonObject.get("compareStatus");
        if (COMPARE_SAME.equals(compareStatus)) {
            return true;
        }
        return false;
    }


}
